import { login } from 'service/actions/user'
import { getUserMsg } from 'service/actions/commonAction'
import { message } from 'antd'
import router from 'umi/router'

export default {
  namespace: 'login',

  state: {
    userMsg: null,
    setLoding: false,
    result: null,
  },

  effects: {
    *login({ payload }, { put, call }){
      // 登录之前清空用户信息缓存
      localStorage.clear()
      yield put({ type: 'updateUserMsg', payload: { setLoding: true}})
      const data = yield call(login, payload)
     
      if (data.userId) {
        message.success('登录成功')
        sessionStorage.setItem('loginInfo', JSON.stringify(data))
        router.push('/workBench')
        yield put({ type: 'updateUserMsg', payload: { setLoding: false}})
        yield put({
          type: 'userMsg',
          payload: { id: data.userId, token: data.access_token}
        })
        // 清空数据，隐藏登录密码或账号错误提示
        yield put({ type: 'clean' })
      } else {
        yield put({ type: 'updateUserMsg', payload: { setLoding: false, result: data }})
      }
      return data
    },
    
    *userMsg({ payload }, { put, call }){                                     
      const data = yield call(getUserMsg, payload)
      if (data.code === '000000') {
        localStorage.setItem('userMsg', JSON.stringify(data.data))
        yield put({
          type: 'updateUserMsg',
          payload: { userMsg: data.data}
        })
        return 
      }
      localStorage.setItem('userMsg', JSON.stringify(null))
      yield put({
        type: 'updateUserMsg',
        payload: { userMsg: null}
      })
    }
  },

  reducers: {
    updateUserMsg(state, { payload }) {
      return { ...state, ...payload }
    },
    // 清空数据验证
    clean(state) {
      return{
        ...state,
        result: null
      }
    }
  }
}
